<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title th:text="${screen.name}"></title>
</head>
<style>
    * {
        padding: 0px;
        margin: 0px auto;
    }

    html,body {
        padding: 0px;
        width: 100%;
        height: 100%;
    }

    iframe {
        float: left;
    }
</style>
<body>

<!-- 大底 -->
<div id="div-viewcomponent-container" th:style="'width:'+${screen.width}+'px;height:'+${screen.height}+'px;;position:relative'">
    <!-- 普通组件 -->
    <div th:class="'div-viewcomponent div-viewcomponent-'+${com.view.code}" th:each="com:${screen.components}"
         th:style="'position: absolute;z-index: 2;background:rgba(255,255,255,0);width:'+${com.position.width}+'px;height:'+${com.position.height}+'px;top:'+${com.position.top}+'px;left:'+${com.position.left}+'px'"
    >
        <iframe
                th:if="${com} ne null"
                th:src="'/screen/preview/view/'+${screen.id}+'/'+${com?.id}+''"
                style="width: 100%; height: 100%; overflow: hidden"
                frameborder="0"
                allowTransparency="true"
        ></iframe>
    </div>

    <!-- 背景组件 -->
    <div  class="'div-viewcomponent-'+${background.view.code}" th:if="${background} ne null" style="width: 100%;height: 100%;position: absolute;left: 0px;top: 0px;z-index: 1;">
        <iframe
                th:src="'/screen/preview/view/'+${screen.id}+'/'+${background?.id}+''"
                style="width: 100%;height: 100%;overflow: hidden;"
                frameborder="0"></iframe>
    </div>
</div>


<script>
    function WebSocketProvider(onReceived)
    {
        //websocket 封装
        var ws={};
        if ("WebSocket" in window)
        {

            function  send(content) {
                try{
                    ws.send(JSON.stringify(content));
                }catch (e) {
                    
                }
            }

            function onopen()
            {

                console.log("数据发送中...");
            };

            function onmessage(evt)
            {
                var received_msg = evt.data;
                var data = JSON.parse(received_msg);
                try{
                    data.data = JSON.parse(data.data);
                }
                catch (e) {

                }
                if(typeof  onReceived == "function")
                {
                    onReceived(data.componentCode,data.data);
                }
                //console.log(data);
                console.log("数据已接收...");
            };

            function onclose()
            {
                // 关闭 websocket
                console.log("连接已关闭...");
                reconnect();
            };

            function connect() {
                // 打开一个 web socket
                ws = new WebSocket("ws://localhost:8085/comm?token=[(${screen.id})]");
                ws.onclose = onclose;
                ws.onopen = onopen;
                ws.onmessage = onmessage;
                ws.onerror = onclose;

            }
            var connectlock = false
            function reconnect() {
                if(connectlock) return;
                connectlock = true;
                setTimeout(function () {
                    connect();
                    connectlock = false;
                },2000)

            }

            connect();
        }

        else
        {
            // 浏览器不支持 WebSocket
            console.log("您的浏览器不支持 WebSocket!");
        }
        return {
            ws:ws,
            send:send
        }
    }

</script>

<script>
    (function () {
        //自适应缩放布局

        if(![(${screen.autoFit})]) return;

        var container =document.getElementById('div-viewcomponent-container');
        container.style.width='100%';
        container.style.height='100%'

        var windowSize = {
            width: [(${screen.width})],//window.innerWidth,
            height:[(${screen.height})] //window.innerHeight,
        };
        var panelsSize=[];
        var panelNodes = document.getElementsByClassName('div-viewcomponent');
        for (let i=0;i<panelNodes.length;i++)
        {
            let panel = panelNodes[i];
            let panelSize = {
                width: panel.clientWidth,
                height: panel.clientHeight,
                left:panel.offsetLeft,
                top:panel.offsetTop,
                node : panel,
            };
            panelsSize.push(panelSize);
        }

        function resize() {

            var newWindowSize = {
                width: window.innerWidth,
                height: window.innerHeight,
            };

            var changePercent={
                width:newWindowSize.width/windowSize.width,
                height:newWindowSize.height/windowSize.height,
            }

            for(let i=0;i<panelsSize.length;i++)
            {
                let panelSize = panelsSize[i];
                var newPanelSize={
                    width:panelSize.width*changePercent.width,
                    height:panelSize.height*changePercent.height,
                    left:panelSize.left*changePercent.width,
                    top:panelSize.top*changePercent.height,

                }

                panelSize.node.style.height = newPanelSize.height+'px';
                panelSize.node.style.width=newPanelSize.width+'px';
                panelSize.node.style.left=newPanelSize.left+'px';
                panelSize.node.style.top=newPanelSize.top+'px';
            }

        }
        resize();

        window.addEventListener('resize',resize)
    })()

</script>

<script>
    var contextObj={};
    (function (context) {
        var panelEventSubscriptions = {};
        var panelUpdateHandlers = {};
        var panelEventListings = {};



        function registerUpdateHandler(panelName, func) {
            panelUpdateHandlers[panelName] = func;
        }

        function subscribeEvent(panelName, event, func) {
            panelEventSubscriptions[panelName] =
                panelEventSubscriptions[panelName] || {};
            panelEventSubscriptions[panelName][event] =
                panelEventSubscriptions[panelName][event] || [];

            var events = panelEventSubscriptions[panelName][event];
            events.push(func);
        }

        //触发更新
        function update(panelName, data) {
            var func = panelUpdateHandlers[panelName] || function () {
            };
            if (typeof func == "function") func(data);
        }

        //初始化socket
        var socket =WebSocketProvider(update);

        //向后台推送数据
        function post(panelName, parameters) {
            var data={
                screenId:"[(${screen.id})]",
                componentCode:panelName,
                parameters:parameters
            }
            //通过 socket 推送数据
            socket.send(data)
        }

        function trigger(panelName, event, data) {
            if (!panelEventSubscriptions[panelName]) return;
            if (!panelEventSubscriptions[panelName][event]) return;
            var events = panelEventSubscriptions[panelName][event];
            for (let i = 0; i < events.length; i++) {
                let func = events[i];
                if (typeof func == "function") setTimeout(function () {
                    func(data)
                });
            }
        }

        function initPanel(options) {
            if (!options.name) {
                console.error("name is null");
                return;
            }
            var panelObj = {
                options: options,
                //事件推送
                trigger(evnetName, data) {
                    trigger(options.name, evnetName, data);
                },
                //后台推送
                post(data) {
                    post(options.name, data);
                },
            };

            if (options.update) {
                registerUpdateHandler(options.name, (data) =>
                    options.update.call(panelObj, data)
                );
            }
            if (options.subscriptions) {
                let panelKeys = Object.keys(options.subscriptions);
                for (let i = 0; i < panelKeys.length; i++) {
                    let panelKey = panelKeys[i];
                    let panel = options.subscriptions[panelKey];
                    let eventKeys = Object.keys(panel);
                    for (let j = 0; j < eventKeys.length; j++) {
                        let eventKey = eventKeys[j];
                        subscribeEvent(panelKey, eventKey, (data) =>
                            panel[eventKey].call(panelObj, data)
                        );
                    }
                }
            }

            if (options.eventDescriptions) {
                panelEventListings[options.name] = options.eventDescriptions;
            }
            console.log(options.name+' inited')
            //初始化完成自动post 一个请求来同步数据
            //panelObj.post([]);
            return panelObj;
        }
        context.initPanel=initPanel;



        //显示面板
        context.showPanels=function (panelNames) {
            panelNames=panelNames||[]
            //显示面板：只显示给定的面板

            //先隐藏所有面板
            var panelElements = document.getElementsByClassName('div-viewcomponent');
            for(let panelIndex =0; panelIndex<panelElements.length;panelIndex++)
            {
                panelElements[panelIndex].style.display='none'
            }

            //显示给定的面板

            for(let panelNameIndex in panelNames)
            {
                panelElements = document.getElementsByClassName('div-viewcomponent-'+panelNames[panelNameIndex]);
                for(let panelIndex =0; panelIndex<panelElements.length;panelIndex++)
                {
                    panelElements[panelIndex].style.display='unset'
                }
            }

        }

        //显示面板
        context.hidePanels=function (panelNames) {
            panelNames=panelNames||[]

            //隐藏给定的面板

            for(let panelNameIndex in panelNames)
            {
                panelElements = document.getElementsByClassName('div-viewcomponent-'+panelNames[panelNameIndex]);
                for(let panelIndex =0; panelIndex<panelElements.length;panelIndex++)
                {
                    panelElements[panelIndex].style.display='none'
                }
            }

        }
    })(contextObj)

</script>

</body>
</html>
